﻿@page "/role"
@using daonaite.Model.system.role
@using daonaite.Model.system.menu
@using daonaite.Model.system.role_menu
@using daonaite.ui.Api
@using daonaite.ui.Util
@inject HttpHelp http
@inject RulesHelp rule
@inject apiRole roleurl
@inject apiMenu menuurl
@inject apiRole_menu rmurl
@inject IMessageService _message
<Card>
    <Form Model="@queryform" Layout="@FormLayout.Inline" OnFinish="queryfinish">
        <FormItem Label="角色名称">
            <Input @bind-Value="@context.roleName"></Input>
        </FormItem>
        <FormItem>
            <Button Type="@ButtonType.Primary" HtmlType="submit">搜索</Button>
        </FormItem>
    </Form>
</Card>
<Card>
    <Button OnClick="handladd">新增</Button>
    <Button Disabled="selects.Count() !=1" OnClick="async e=>{await handlupdate(selects.First().id); }">编辑</Button>
    <Popconfirm Title="确认删除本条数据?"
            OnConfirm="async e=>{await pldelete();}">
                <Button Disabled="selects.Count() ==0">删除</Button>
            </Popconfirm>
    <Button>导入</Button>
    <Button>导出</Button>
</Card>
<Card>
    <Table DataSource="@listrole" @bind-SelectedRows="@selects">
        <Selection></Selection>
        <PropertyColumn Property="c=>c.id" Title="序号"></PropertyColumn>
        <PropertyColumn Property="c=>c.roleName" Title="角色名称"></PropertyColumn>
        <PropertyColumn Property="c=>c.dataPermissions" Title="数据权限">
                @switch(context.dataPermissions)
                {
                    case "0":
                        {
                            <Tag Color="processing">所有</Tag>
                            break;
                        }
                        case "1":
                        {
                            <Tag Color="processing">本部门</Tag>
                            break;
                        }
                        case "2":
                        {
                            <Tag Color="processing">部门及以下</Tag>
                            break;
                        }
                        case "3":
                        {
                            <Tag Color="processing">仅自己</Tag>
                            break;
                        }
                }
        </PropertyColumn>
        <ActionColumn Title="操作">
            <Button OnClick="async e=>{await handlupdate(context.id);}">编辑</Button>
            <Popconfirm Title="确认删除本条数据?"
            OnConfirm="async e=>{await handldelete(context.id);}">
                <Button>删除</Button>
            </Popconfirm>
            <Button OnClick="async e=>{ await handlquanxian(context.id); }">菜单权限</Button>
        </ActionColumn>
    </Table>
</Card>
<Modal Title="@rolemodal.title" Visible="@rolemodal.open" OnCancel="rolemodal.cancel" Footer="null">
    <Form Model="@rolemodal.data" ValidateMode="FormValidateMode.Rules" OnFinish="rolemodalfinish" LabelColSpan="4">
        <FormItem Label="角色名称" Rules="@rule.required("请输入角色名称")">
            <Input @bind-Value="@context.roleName" Placeholder="请输入角色名称"></Input>
        </FormItem>
        <FormItem Label="数据权限">
            <Select DataSource="@quanxians" @bind-Value="@context.dataPermissions" 
            ValueProperty="c=>c.val"
            LabelProperty="c=>c.name"></Select>
        </FormItem>
        <FormItem WrapperColOffset="4">
            <Button Type="@ButtonType.Primary" HtmlType="submit">提交</Button>
            <Button OnClick="rolemodal.cancel">取消</Button>
        </FormItem>
    </Form>
</Modal>
<!--权限弹框-->
<Modal Title="@menumodal.title" Visible="@menumodal.open" OnCancel="menumodal.cancel" OnOk="menmodalok">
    <Tree ShowIcon
        Multiple ="true" Checkable="true"  DefaultExpandAll="true" 
          DataSource="@menumodal.data"
          DefaultCheckedKeys="@DefaultCKs"
          TitleExpression="x => x.DataItem.menuName"
          KeyExpression="x=>x.DataItem.id.ToString()"
          ChildrenExpression="x => x.DataItem.child"
          DefaultExpandParent="true"
          @bind-CheckedKeys="@CheckedKeys"
    >
      </Tree>
</Modal>

@code {
    private Dto_role queryform = new Dto_role();
    private IEnumerable<sys_role> listrole = new List<sys_role>();
    IEnumerable<sys_role> selects = new List<sys_role>();

    private string[] CheckedKeys = new string[] { };
    private string[] DefaultCKs = new string[] { };

    private class Modals<T>
    {
        public int id{ get; set; }
        public string title { get; set; } = "";
        public bool open { get; set; } = false;
        public T data { get; set; }

        public void cancel()
        {
            title = "";
            open = false;
        }
    }

    private class quanxian
    {
        public string name{ get; set; }
        public string val{ get; set; }
    }

    private List<quanxian> quanxians = new List<quanxian>();

    Modals<sys_role> rolemodal = new Role.Modals<sys_role>();
    Modals<List<sys_menu>> menumodal = new Role.Modals<List<sys_menu>>();


    protected override async Task OnInitializedAsync()
    {
        quanxians.Add(new quanxian() { name = "所有",val="0" });
        quanxians.Add(new quanxian() { name = "本部门",val="1" });
        quanxians.Add(new quanxian() { name = "部门及以下",val="2" });
        quanxians.Add(new quanxian() { name = "仅自己",val="3" });
        await queryfinish();
        await base.OnInitializedAsync();
    }

    private async Task queryfinish()
    {
        var result = await http.posttAsync<IEnumerable<sys_role>?, Dto_role>(roleurl.select, queryform);
        if (result.Code == 200)
        {
            listrole = result.Data;
        }
    }

    private async Task rolemodalfinish()
    {
        if (rolemodal.data.id > 0) //编辑
        {
            var result = await http.posttAsync<int?, sys_role>(roleurl.update, rolemodal.data);
            if (result.Code == 200)
            {
                rolemodal.title = "";
                rolemodal.open = false;
                _message.Success("修改成功");
                await queryfinish();
            }
        }
        else //新增
        {
            var result = await http.posttAsync<int?, sys_role>(roleurl.add, rolemodal.data);
            if (result.Code == 200)
            {
                rolemodal.title = "";
                rolemodal.open = false;
                _message.Success("新增成功");
                await queryfinish();
            }
        }
    }

    private void handladd()
    {
        rolemodal.title = "添加角色";
        rolemodal.open = true;
        rolemodal.data = new sys_role();
    }

    private async Task handlupdate(int id)
    {
        var result = await  http.getAsync<sys_role?>($"{roleurl.get}?id={id}");
        if(result.Code == 200)
        {
            rolemodal.title = "编辑角色";
            rolemodal.open = true;
            rolemodal.data = result.Data;
        }
    }

    private async Task handldelete(int id)
    {
        var result = await  http.getAsync<int?>($"{roleurl.delete}?id={id}");
        if(result.Code == 200)
        {
            _message.Success("删除成功");
            await queryfinish();
        }
    }

    private async Task pldelete()
    {
        foreach (var item in selects)
        {
            var result = await  http.getAsync<int?>($"{roleurl.delete}?id={item.id}");
        }
        _message.Success("删除成功");
        await queryfinish();
    }

    /// <summary>
    /// 查看权限信息, 根据role id 查询现有的
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    private async Task handlquanxian(int id)
    {
        var result = await  http.posttAsync<List<sys_menu>?,Dto_menu>(menuurl.Gettreemenu,new Dto_menu());
        if(result.Code == 200)
        {
            // 查询默认选中的菜单
            var rmresult = await http.getAsync<sys_role_menu?>($"{rmurl.getbyrole}?roleId={id}");
            if(rmresult.Code == 200 && rmresult.Data !=null)
            {
                if(!string.IsNullOrEmpty(rmresult.Data.menuIds))
                {
                    DefaultCKs = rmresult.Data.menuIds.Split(",");
                }
            }
            // 查询默认选中的按钮

            menumodal.id = id;
            menumodal.title = "菜单权限";
            menumodal.open = true;
            menumodal.data = result.Data;
        }
    }

    private async Task menmodalok()
    {
        string nr = string.Join(",", CheckedKeys);
        sys_role_menu canshu = new sys_role_menu();
        canshu.menuIds = nr;
        canshu.roleId = menumodal.id;
        var result = await http.posttAsync<int?, sys_role_menu>(rmurl.update_mensid,canshu);
        if(result.Code == 200)
        {
            _message.Success("修改完成");
            menumodal.id = 0;
            menumodal.title = "";
            menumodal.open = false;
            menumodal.data = new List<sys_menu>();
        }

    }
}
